<template>
  <div>
    <a-row>
      <a-col :span="12">
        <a-input
          :placeholder="placeholder"
          @click="initImg()"
          @keyup="onKey($event)"
          v-model:value="selfValue"
        >
        </a-input>
      </a-col>
    </a-row>
  </div>
  <div>
    <a-row>
      <!-- 验证码图片 -->
      <a-col :span="12"> <img :src="captchaUrl" @click="clearImg()" v-if="captchaUrl" /> </a-col>
    </a-row>
  </div>
</template>

<script lang="ts">
  import { appSessionService } from '/@/shared/abp';
  import { AppComponentBase } from '/@/shared/component-base';
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'Captcha',
    mixins: [AppComponentBase],
    props: {
      modelValue: {
        type: String, // 实际传过来的类型
      },
      type: {
        type: String, // 实际传过来的类型
      },
      primaryKey: {
        type: String, // 实际传过来的类型
      },
      placeholder: {
        type: String, // 实际传过来的类型
      },
    },
    emits: ['update:modelValue'],
    data() {
      return {
        defaultValue: '',
        captchaUrlVal: '',
        oldPrimaryKey: '',
        primaryKeyVal: '',
        appSession: appSessionService,
        lastKey: '',
      };
    },
    computed: {
      selfValue: {
        // 读写计算属性
        get() {
          return this.modelValue;
        },
        set(val) {
          this.$emit('update:modelValue', val);
        },
      },
      captchaUrl() {
        return this.captchaUrlVal;
      },
      checkKey() {
        return this.oldPrimaryKey && this.oldPrimaryKey === this.primaryKeyVal;
      },
    },
    watch: {
      primaryKey(val) {
        this.primaryKeyVal = val;
      },
      modelValue(val: string) {
        // 监听props变更，更新
        this.selfValue = val;
      },
    },
    methods: {
      initImg() {
        // 初始化验证码图片
        if (!this.primaryKeyVal || this.primaryKeyVal === '' || this.captchaUrl || this.checkKey) {
          return;
        }
        this.clearImg();
      },
      clearImg() {
        // 重置验证码图片
        if (!this.primaryKeyVal || this.primaryKeyVal === '') {
          // 未输入验证码key
          return;
        }

        let tid = appSessionService.tenantId;
        if (!tid) {
          tid = 0;
        }
        this.lastKey = this.primaryKeyVal;

        // 后端统一处理，基于租户的验证码
        let tenantId: any = this.appSession.tenantId;
        if (!tenantId) {
          tenantId = '';
        }
        this.oldPrimaryKey = this.primaryKeyVal;
        let timestamp = new Date().getTime();
        const queryParams = `tenantOrUserName=${this.primaryKeyVal}&tenantId=${tenantId}&captchaSettingType=${this.type}&timestamp=${timestamp}`;
        this.captchaUrlVal = `${this.$apiUrl}/api/TokenAuth/GenerateCaptcha?${queryParams}`;
      },
      onKey(e: any): void {
        // tab触发到此控件
        if (e.key === 'Tab') {
          this.initImg();
        }
      },
    },
  });
</script>

<style lang="less" scoped>
  @import './captcha.less';
</style>
